<template>
  <div style="display: flex;vertical-align: middle">
    <el-upload class="upload"
               :action="uploadApi"
               :accept="fileType"
               :show-file-list="showFiles"
               :file-list="fileLists"
               :on-remove="fileRemove"
               :drag="drag"
               :before-upload="beforeUpload"
               :on-success="uploadSuccess"
               :on-error="uploadFailed"
               :headers="headers"
               :data="sendData"
               v-bind="$attrs"
               v-on="$listeners"
               v-if="btnDisplay">
      <vxe-button ref="upload" :type="type" v-if="classType && btnDisplay && !drag" :size="btnSize" :content="label"
                  class="iconCircle" :icon="btnIcon" :title="tips" :menuCode="menuCode" :perms="perms" :openPerms="openPerms"></vxe-button>
      <vxe-button ref="upload" :type="type" v-if="!classType && btnDisplay && !drag" :size="btnSize" :content="label"
                  :label="label" :icon="btnIcon" :menuCode="menuCode" :perms="perms" :openPerms="openPerms"></vxe-button>
      <i class="el-icon-upload" v-if="drag"></i>
      <div v-if="drag" class="el-upload__text">将文件拖到此处或者点击上传</div>
    </el-upload>
    <span v-if="value && showFileName">
      <a :href="value" target="_blank" style="line-height: 33px">{{newFileName}}</a>
    </span>
  </div>
</template>

<script>
// import AuthButton from '@/components/auth/authButton'
export default {
  inheritAttrs: false,
  props: {
    showFileName: {
      type: Boolean,
      default () {
        return true
      }
    },
    value: {
      type: String,
      default () {
        return ''
      }
    },
    // 文件名长度限制
    fileNameSize: {
      type: Number,
      default () {
        return null
      }
    },
    // 所属菜单Code-->全局唯一
    menuCode: {
      type: String,
      default: null
    },
    // 按钮权限标识，外部使用者传入
    perms: {
      type: String,
      default: null
    },
    // 文件ID
    fileID: {
      type: [String, Number],
      default: function () {
        return null
      }
    },
    showFiles: {
      type: Boolean,
      default: false
    },
    // 文件名
    fileName: {
      type: String,
      default: function () {
        return null
      }
    },
    // 所属类型CODE
    belongCode: {
      type: String,
      // required: true,
      default: function () {
        return 'GYS'
      }
    },
    // 是否拖拽
    drag: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 所属业务ID
    belongID: {
      type: String,
      // required: true,
      default: function () {
        return null
      }
    },
    // 限制文件类型
    fileType: {
      type: String,
      default: function () {
        return null
      }
    },
    // 限制文件大小(M)
    fileSize: {
      type: Number,
      default: function () {
        return 50
      }
    },
    // 文件管理服务上传地址
    uploadApi: {
      type: String,
      required: false
    },
    // 行数据
    rowData: {
      type: Object,
      default: function () {
        return null
      }
    },
    // 行号
    rowIndex: {
      type: Number,
      default: function () {
        return null
      }
    },
    // 按钮大小
    btnSize: {
      type: String,
      default: function () {
        return 'small'
      }
    },
    btnDisplay: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // index
    index: {
      type: Number,
      default: function () {
        return null
      }
    },
    // 上传按钮显示内容
    uploadName: {
      type: String,
      default: function () {
        return '上 传'
      }
    },
    // 重新上传按钮显示内容
    reUploadName: {
      type: String,
      default: function () {
        return '重新上传'
      }
    },
    // 是否开启鉴权，默认关闭
    openPerms: {
      type: Boolean,
      default () {
        return false
      }
    },
    title: { // 按钮提示
      type: String,
      default: '上传'
    },
    reTitle: {
      type: String,
      default: function () {
        return '重新上传'
      }
    },
    classType: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    type: {  // 按钮类型
      type: String,
      default: function () {
        return ''
      }
    },
    icon: {
      type: String,
      default: function () {
        return ''
      }
    }
  },
  data () {
    return {
      fullscreenLoading: false,
      newFileName: this.fileName || '预览',
      headers: {
        Authorization: 'Bearer ' + this.$store.getters.token,
        token: this.$store.getters.token,
        tenantId: this.$store.getters.tenantId,
        client: this.$store.getters.sysId
      },
      fileLists: []
    }
  },
  computed: {
    sendData: function () {
      return {
        belongCode: this.belongCode,
        belongID: this.belongID
      }
    },
    currentFileId: {
      get: function () {
        return this.fileID
      },
      set: function (val) {
        return this.$emit('update:fileID', val)
      }
    },
    label () {
      // 数据库字段不能为空，默认为零
      return this.UtilJs.isEmpty(this.currentFileId) || this.currentFileId === '0' ? this.uploadName : this.reUploadName
    },
    tips () {
      return this.UtilJs.isEmpty(this.currentFileId) || this.currentFileId === '0' ? this.title : this.reTitle
    },
    btnIcon () {
      if (this.UtilJs.isEmpty(this.icon)) {
        return this.classType ? 'iconfont iconycshangchuan1' : 'iconfont iconycshangchuan'
      } else {
        return this.icon
      }
    }
  },
  methods: {
    // 设置名
    setFileName (fileName) {
      this.newFileName = fileName
    },
    // 手动触发按钮上传，供外部调用
    upload () {
      this.$refs['upload'].$el.click()
    },
    beforeUpload (file) {
      // 判断文件名长度
      if ((!this.UtilJs.isNull(this.fileNameSize)) && file.name.length > this.fileNameSize) {
        this.warning(`已超出上传文件名最大限制${this.fileNameSize}个字符`)
        return false
      }
      if (!this.UtilJs.isNull(this.fileSize) && file.size / 1024 > this.fileSize * 1024) {
        this.warning(`已超出上传文件最大限制${this.fileSize}M`)
        return false
      }
      var fileType = '.' + file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
      var banFileTypes = ['.exe', '.bat', '.cmd', '.sh', '.py']
      var banFileTypeFlag = 0
      banFileTypes.forEach(item => {
        if (item === fileType) {
          banFileTypeFlag = 1
        }
      })
      if (banFileTypeFlag === 1) {
        this.warning('不允许上传' + fileType.substring(fileType.lastIndexOf('.') + 1) + '文件')
        return false
      }
      if (!this.UtilJs.isNull(this.fileType)) {
        var fileTypeFlag = 0
        var fileTypeList = this.fileType.toLowerCase().split(',')
        fileTypeList.forEach(it => {
          if (fileType === it) {
            fileTypeFlag = 1
          }
        })
        if (fileTypeFlag === 0) {
          this.warning('只能上传' + this.fileType.toLowerCase().replace(/\./g, '') + '文件')
          return false
        }
      }
      let returnData = {}
      returnData.rowData = this.rowData
      returnData.rowIndex = this.rowIndex
      returnData.index = this.index
      this.$emit('beforeUpload', returnData)
      this.fullscreenLoading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return true
    },
    fileRemove (file, fileList) {
      this.$emit('fileRemove', fileList)
    },
    uploadSuccess (response, file, fileList) {
      if (response.error !== 0) {
        this.fullscreenLoading.close()
        this.error(response.message)
        return
      }
      let returnData = {}
      returnData.rowData = this.rowData
      returnData.rowIndex = this.rowIndex
      returnData.index = this.index
      returnData.fileID = response.url
      returnData.fileName = file.name
      this.newFileName = file.name
      console.log(returnData, this.rowData, fileList)
      this.$emit('input', returnData.fileID)
      this.$emit('uploadSuccess', returnData, this.rowData, fileList)
      this.fullscreenLoading.close()
    },
    uploadFailed (err, file, fileList) {
      let returnData = {}
      returnData.rowData = this.rowData
      returnData.rowIndex = this.rowIndex
      returnData.index = this.index
      this.$emit('uploadFailed', returnData, this.rowData, fileList)
      this.fullscreenLoading.close()
    }
  }
}
</script>

<style scoped>
  .upload{
    display:inline-block;
    margin: 0 9px 0 1px;
  }
</style>
